#!/bin/bash

function usage {
 cat<<EOF>&2
Overview

 Run this script as root in /opt/microchip to repair file and
 directory permissions for multiple system users.

Status

 This code covers the most obvious cases, but might change files to
 read perms (644) that need to be executable (755).  Currently it only
 knows about linux (user) files.  Please feel free to file an
 enhancement request at
  http://code.google.com/p/digivac/issues

No Warranty

 Use this script at your own risk.  Changing filesystem permissions
 can render your SDK unusable.

Author

 John Pritchard  mailto:jdp@digivac.net

License

 CC-BY  http://creativecommons.org/licenses/by/2.0/


Usage

 $0 --help

Description

 This message.


Usage

 $0 --list

Description

 List files with "X" prefix repair mode.  Makes no changes to the file
 system.


Usage

 $0 --repair

Description

 Assumes local directory location '/opt/microchip' or equivalent to
 perform directory and file ownership and permissions repair.

 Performs changes to the file system.  See also 'list' usage.

EOF
 exit 1
}

function isFiletypeB {
 if [ -n "$(echo "${1}" | egrep '/bin/')" ]
 then
  return 0;
 else
  return 1;
 fi
}

function isFiletypeX {
 fext=$(echo "${1}" | sed 's/.*\.//')
 if [ -n "${fext}" ]
 then
  case "${fext}" in
   pdf|so|dll|bat|cat|chm|dll|dylib|exe|inf|info|jar|jnilib|LanguageTool|LanguageToolSuite|lkr|pdf)
     return 1;;
   sh)
     return 0;;
   *)
     if isFiletypeB "${1}"
     then
      return 0;
     else
      return 1;
     fi ;;
  esac
 elif isFiletypeB "${1}"
 then
  return 0;
 else
  return 1;
 fi
}

function list {

 for file in $(find . -type f | sed 's% %#%g' )
 do
  filn=$(echo $file | sed 's/#/ /g')

  if isFiletypeX "${filn}"
  then 
   echo "X ${filn}"
  fi
 done
}

function repair {

 chown -Rh root:root .

 for dir in $(find . -type d | sed 's% %#%g' )
 do
  dirn=$(echo $dir | sed 's/#/ /g')
  echo "D ${dirn}"
  chmod 755 "${dirn}"
 done

 for file in $(find . -type f | sed 's% %#%g' )
 do
  filn=$(echo $file | sed 's/#/ /g')

  if isFiletypeX "${filn}"
  then 
   echo "X ${filn}"
   chmod 755 "${filn}"
  else
   echo "F ${filn}"
   chmod 644 "${filn}"
  fi
 done
}

if [ -n "${1}" ]
then
 case "${1}" in

  *list)
    list   ;;

  *repair)
    repair ;;

  *)
    usage  ;;
 esac 
else
 usage
fi
